package de.uni.muenster.idw2.location;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
import de.uni.muenster.idw2.location.bluetooth.service.PositioningService;
import de.uni.muenster.idw2.location.bluetooth.service.PositioningServiceInterface;

public class BluetoothController {
	// for binding to the positioning service.
	private PositioningServiceInterface positioningService;
	private boolean boundToService = false;
	private final Activity activity;

	// TODO: the context should be established before calling any of the
	// Bluetooth related methods.
	
	public BluetoothController(Activity activity){
		this.activity = activity;
		
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className,	IBinder service) {
			PositioningService.PositioningBinder binder = (PositioningService.PositioningBinder) service;
			// configuring the service
			positioningService = binder.getService();
			positioningService.setSaveMeasurements(true);
			positioningService.startPositioning();
			boundToService = true;
		}

		public void onServiceDisconnected(ComponentName arg0) {
			boundToService = false;
		}
	};

	public void startService() {
		try {
			Intent intent = new Intent(activity,
					PositioningService.class);
			/* getApplicationContext() */
			activity.bindService(
					intent, serviceConnection, Context.BIND_AUTO_CREATE);
		} catch (Exception e) {
			Log.e("Error", "starting a service");
		}
	}

	public void stopService() {
		/* getApplicationContext() */activity
				.unbindService(serviceConnection);
	}
}
